/**
 * @file Serial.hh
 * @author Simon Gustafsson (www.simong.se)
 **/

#ifndef SERIAL_HH_
#define SERIAL_HH_

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <termios.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define BAUDRATE B57600

/**
 * Class which initializes a serial port. Just the stuff needed for my xy-mill project...
 *
 * Main source: http://tldp.org/HOWTO/Serial-Programming-HOWTO/x115.html
 */
class Serial{
	int fd;
	struct termios oldtio,newtio;
public:
	/** Open and initialize serial port dev 
	 * @note prints an error message and calls exit(-1) if the port could not be opened. */
	Serial(const char* dev = "/dev/ttyUSB0"){
		//int res;

		fd = open(dev, O_RDWR | O_NOCTTY ); 
		if (fd <0) {perror(dev); exit(-1); }

		tcgetattr(fd,&oldtio); /* save current port settings */

		bzero(&newtio, sizeof(newtio));
		newtio.c_cflag = BAUDRATE | CS8 | CLOCAL | CREAD;
		newtio.c_iflag = IGNPAR;
		newtio.c_oflag = 0;

		/* set input mode (non-canonical, no echo,...) */
		newtio.c_lflag = 0;

		newtio.c_cc[VTIME]    = 0;   /* inter-character timer unused */
		newtio.c_cc[VMIN]     = 0;   /* 1 = blocking read until 1 chars received */

		tcflush(fd, TCIFLUSH);
		tcsetattr(fd,TCSANOW,&newtio);
	}
	
	/** restore previous termios. */
	~Serial(){
		tcsetattr(fd,TCSANOW,&oldtio);
	}
	
	/** Get file descriptor of opened and initialized serial port */
	operator int(){
		return fd;
	}
};


#endif /*SERIAL_HH_*/
